<template>
  <div class="register-container">
    <!-- 左侧品牌区域 -->
    <div class="left-panel">
      <!-- 图片 -->
      <img 
        src="../static/background.png" 
        alt="background" 
        class="background-image"
      />
      
      <!-- 左上角品牌信息 -->
      <div class="brand-header">
        <div class="logo-icon">
          <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <path d="M22 20v-5h-3a5 5 0 0 1-5-5v-3a5 5 0 0 1 5-5h3v13z"></path>
            <path d="M18 10a3 3 0 0 1 3 3v4a3 3 0 0 1-3 3h-4l-8-10v-3h6a3 3 0 0 1 3 3z"></path>
            <path d="m12 12-2-1-1-1"></path>
          </svg>
        </div>
        <div class="brand-info">
          <h1 class="brand-title">流浪动物救助系统</h1>
          <p class="brand-subtitle">加入我们，一起守护每一个生命</p>
        </div>
      </div>

      <!-- 底部公司信息 -->
      <div class="company-info">
        <p class="company-name">流浪动物救助中心</p>
        <p class="company-slogan">用爱心呵护每一个生命</p>
      </div>
    </div>

    <!-- 右侧注册区域 -->
    <div class="right-panel">
      <div class="register-content">
        <!-- 注册关闭提示 -->
        <div v-if="!registrationEnabled" class="registration-disabled">
          <div class="disabled-icon">
            <el-icon :size="80"><Lock /></el-icon>
          </div>
          <h2 class="disabled-title">注册功能已关闭</h2>
          <p class="disabled-description">
            系统当前暂不接受新用户注册
          </p>
          <p class="disabled-tip">
            如需注册账号，请联系管理员
          </p>
          <div class="disabled-actions">
            <el-button type="primary" size="large" @click="goToLogin">
              返回登录页
            </el-button>
          </div>
        </div>

        <!-- 注册表单 -->
        <template v-else>
          <div class="register-header">
            <h2 class="register-title">注册账号</h2>
            <p class="register-subtitle">欢迎加入我们，开始您的爱心之旅</p>
          </div>

          <el-form :model="form" :rules="rules" ref="registerForm" class="register-form">
          <!-- 手机号（必填） -->
          <el-form-item prop="phone">
            <el-input 
              v-model="form.phone" 
              placeholder="请输入手机号"
              size="large"
              class="input-item"
            >
              <template #prefix>
                <el-icon class="input-icon"><Phone /></el-icon>
              </template>
            </el-input>
          </el-form-item>

          <!-- 用户名（必填，只允许英文） -->
          <el-form-item prop="username">
            <el-input 
              v-model="form.username" 
              placeholder="请输入用户名（仅限英文）"
              size="large"
              class="input-item"
            >
              <template #prefix>
                <el-icon class="input-icon"><User /></el-icon>
              </template>
            </el-input>
          </el-form-item>

          <!-- 密码 -->
          <el-form-item prop="password">
            <el-input 
              v-model="form.password" 
              type="password" 
              placeholder="请输入密码"
              size="large"
              class="input-item"
              show-password
            >
              <template #prefix>
                <el-icon class="input-icon"><Lock /></el-icon>
              </template>
            </el-input>
          </el-form-item>

          <!-- 确认密码 -->
          <el-form-item prop="confirm">
            <el-input 
              v-model="form.confirm" 
              type="password" 
              placeholder="请再次输入密码"
              size="large"
              class="input-item"
              show-password
            >
              <template #prefix>
                <el-icon class="input-icon"><Lock /></el-icon>
              </template>
            </el-input>
          </el-form-item>

          <!-- 验证码 -->
          <el-form-item prop="captcha" style="margin-top: 8px;">
            <div class="captcha-row">
              <el-input 
                v-model.number="form.captcha" 
                placeholder="验证码"
                size="large"
                class="captcha-input"
              >
                <template #prefix>
                  <el-icon class="input-icon"><Grid /></el-icon>
                </template>
              </el-input>
              <div class="captcha-box" @click="generateCaptcha">
                <canvas
                  ref="captchaCanvas"
                  width="100"
                  height="40"
                  class="captcha-canvas"
                  style="width: 100px; height: 40px;"
                ></canvas>
              </div>
            </div>
          </el-form-item>

          <!-- 30天自动登录和隐私服务 -->
          <div class="checkbox-row">
            <el-checkbox v-model="rememberLogin" class="remember-checkbox">
              30天自动登录
            </el-checkbox>
            <el-checkbox v-model="privacyAgree" class="privacy-checkbox">
              我已阅读并同意<span class="privacy-link" @click="showPrivacyDialog = true">《隐私服务协议》</span>
            </el-checkbox>
          </div>

          <!-- 注册按钮 -->
          <el-button 
            type="primary" 
            @click="register" 
            size="large"
            class="register-button"
          >
            立即注册
          </el-button>

          <!-- 登录链接 -->
          <div class="action-links">
            <span class="login-link">
              已有账号？
              <span @click="$router.push('/login')">立即登录</span>
            </span>
          </div>
        </el-form>
        </template>
      </div>
    </div>

    <!-- 隐私协议弹窗 -->
    <el-dialog
      v-model="showPrivacyDialog"
      title="隐私服务协议"
      width="800px"
    >
      <div class="privacy-content">
        <h3>一、信息收集</h3>
        <p>我们可能收集以下信息：</p>
        <ul>
          <li>个人信息：姓名、手机号码、邮箱地址等</li>
          <li>设备信息：IP地址、浏览器类型等</li>
          <li>使用信息：登录记录、操作日志等</li>
        </ul>

        <h3>二、信息使用</h3>
        <p>我们使用收集的信息用于：</p>
        <ul>
          <li>提供和改进我们的服务</li>
          <li>与您沟通，包括服务通知和客户支持</li>
          <li>检测和防范安全威胁、欺诈或非法活动</li>
        </ul>

        <h3>三、信息保护</h3>
        <p>我们采用行业标准的安全措施保护您的信息，包括：</p>
        <ul>
          <li>数据加密传输和存储</li>
          <li>访问控制和权限管理</li>
          <li>定期安全审计和更新</li>
        </ul>

        <h3>四、信息分享</h3>
        <p>我们不会向第三方出售、交易或转让您的个人信息，除非：</p>
        <ul>
          <li>获得您的明确同意</li>
          <li>法律法规要求</li>
          <li>保护我们的权利和财产</li>
        </ul>

        <h3>五、Cookie使用</h3>
        <p>我们使用Cookie和类似技术来：</p>
        <ul>
          <li>记住您的登录状态和偏好设置</li>
          <li>分析网站流量和用户行为</li>
          <li>提供个性化内容和广告</li>
        </ul>

        <h3>六、联系我们</h3>
        <p>如您对本隐私政策有任何疑问，请联系我们：</p>
        <p>邮箱：privacy@animal-rescue.org<br/>电话：400-123-4567</p>
      </div>
      <template #footer>
        <el-button type="primary" @click="acceptPrivacy">我已阅读并同意</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import axios from "axios";
import { User, Lock, Grid, Phone } from "@element-plus/icons-vue";
import { ElMessage } from 'element-plus';

export default {
  components: {
    User,
    Lock,
    Grid,
    Phone,
  },
  data() {
    return {
      registrationEnabled: true, // 注册功能是否开启
      form: {
        phone: "",
        username: "",
        password: "",
        confirm: "",
        captcha: "",
      },
      captchaAnswer: 0,
      rememberLogin: true,
      privacyAgree: true,
      showPrivacyDialog: false,
      rules: {
        phone: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号", trigger: "blur" }
        ],
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 2, max: 20, message: "用户名长度在2到20个字符", trigger: "blur" },
          { pattern: /^[a-zA-Z0-9_]+$/, message: "用户名只能包含英文、数字和下划线", trigger: "blur" }
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 6, max: 20, message: "密码长度在6到20个字符", trigger: "blur" }
        ],
        confirm: [
          { required: true, message: "请再次输入密码", trigger: "blur" },
          { validator: this.validateConfirmPassword, trigger: "blur" }
        ],
        captcha: [
          { required: true, message: "请输入验证码", trigger: "blur" }
        ]
      }
    };
  },
  mounted() {
    this.checkRegistrationStatus();
    this.generateCaptcha();
  },
  methods: {
    // 检查注册功能是否开启
    async checkRegistrationStatus() {
      try {
        const res = await axios.get('http://localhost:8080/api/admin/system-setting/key/user_registration');
        if (res.data.code === 200 && res.data.data) {
          // 检查设置值或状态，1表示启用，0表示禁用
          const settingValue = res.data.data.settingValue;
          const status = res.data.data.status;
          // 如果设置值为'0'或状态为0，则关闭注册
          this.registrationEnabled = !(settingValue === '0' || status === 0);
        }
      } catch (error) {
        console.error('检查注册功能状态失败:', error);
        // 如果检查失败，默认允许注册
        this.registrationEnabled = true;
      }
    },
    // 返回登录页
    goToLogin() {
      this.$router.push('/login');
    },
    // 验证确认密码
    validateConfirmPassword(rule, value, callback) {
      if (value !== this.form.password) {
        callback(new Error("两次密码不一致"));
      } else {
        callback();
      }
    },
    
    // 生成验证码
    generateCaptcha() {
      const canvas = this.$refs.captchaCanvas;
      const ctx = canvas.getContext("2d");

      const num1 = Math.floor(Math.random() * 10);
      const num2 = Math.floor(Math.random() * 10);
      const operators = ["+", "-", "*"];
      const op = operators[Math.floor(Math.random() * operators.length)];

      switch (op) {
        case "+": this.captchaAnswer = num1 + num2; break;
        case "-": this.captchaAnswer = num1 - num2; break;
        case "*": this.captchaAnswer = num1 * num2; break;
      }

      ctx.fillStyle = "#ffffff";
      ctx.fillRect(0, 0, canvas.width, canvas.height);

      ctx.font = "bold 18px Arial";
      ctx.fillStyle = "#303133";
      ctx.fillText(`${num1} ${op} ${num2} = ?`, 12, 25);

      for (let i = 0; i < 50; i++) {
        ctx.fillStyle = `rgba(${Math.random()*255},${Math.random()*255},${Math.random()*255},0.5)`;
        ctx.fillRect(Math.random()*canvas.width, Math.random()*canvas.height, 2, 2);
      }

      for (let i = 0; i < 3; i++) {
        ctx.strokeStyle = `rgba(${Math.random()*255},${Math.random()*255},${Math.random()*255},0.3)`;
        ctx.lineWidth = 1;
        ctx.beginPath();
        ctx.moveTo(Math.random()*canvas.width, Math.random()*canvas.height);
        ctx.lineTo(Math.random()*canvas.width, Math.random()*canvas.height);
        ctx.stroke();
      }

      this.form.captcha = "";
    },
    
    // 接受隐私协议
    acceptPrivacy() {
      this.privacyAgree = true;
      this.showPrivacyDialog = false;
    },

    async register() {
      // 再次检查注册功能是否开启
      if (!this.registrationEnabled) {
        ElMessage.warning('注册功能已关闭，请联系管理员');
        return;
      }

      // 验证表单
      this.$refs.registerForm.validate(async (valid) => {
        if (!valid) {
          ElMessage.error("请完善注册信息");
          this.generateCaptcha();
          return;
        }

        // 验证验证码
        if (Number(this.form.captcha) !== this.captchaAnswer) {
          ElMessage.error("验证码错误");
          this.generateCaptcha();
          return;
        }

        try {
          const res = await axios.post("http://localhost:8080/api/auth/register", {
            phone: this.form.phone,
            username: this.form.username,
            password: this.form.password
          });

          if (res.data.code === 200) {
            ElMessage.success("注册成功，正在跳转到登录页...");
            setTimeout(() => {
              this.$router.push("/login");
            }, 1500);
          } else {
            ElMessage.error(res.data.msg);
            this.generateCaptcha();
          }
        } catch (error) {
          ElMessage.error("注册失败，请检查服务器或网络");
          this.generateCaptcha();
        }
      });
    },
  },
};
</script>

<style scoped>
.register-container {
  display: flex;
  height: 100vh;
  overflow: hidden;
  background: #f8f9fa;
}

/* 左侧品牌区域 */
.left-panel {
  width: 60%;
  position: relative;
  overflow: hidden;
  background: #fafbfc;
  display: flex;
  flex-direction: column;
}

.background-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  filter: brightness(1.1) saturate(1.1) contrast(0.95);
  mask-image: linear-gradient(to right, rgba(0,0,0,1) 80%, rgba(0,0,0,0.2) 92%, rgba(0,0,0,0) 100%);
  -webkit-mask-image: linear-gradient(to right, rgba(0,0,0,1) 80%, rgba(0,0,0,0.2) 92%, rgba(0,0,0,0) 100%);
}

.brand-header {
  position: absolute;
  top: 50px;
  left: 50px;
  z-index: 3;
  display: flex;
  align-items: center;
  gap: 16px;
}

.logo-icon {
  width: 56px;
  height: 56px;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  flex-shrink: 0;
}

.logo-icon svg {
  color: #52c41a;
}

.brand-info {
  text-align: left;
}

.brand-title {
  font-size: 36px;
  font-weight: 700;
  margin: 0 0 8px 0;
  color: #1a1a1a;
  line-height: 1.2;
}

.brand-subtitle {
  font-size: 15px;
  margin: 0;
  color: #4a5568;
  font-weight: 400;
  line-height: 1.4;
}

.company-info {
  position: absolute;
  bottom: 60px;
  left: 50px;
  z-index: 3;
  text-align: left;
}

.company-name {
  font-size: 22px;
  font-weight: 600;
  margin: 0 0 6px 0;
  color: #1a1a1a;
  text-shadow: 0 1px 4px rgba(255, 255, 255, 0.3);
}

.company-slogan {
  font-size: 13px;
  margin: 0;
  color: #606266;
  font-weight: 400;
}

/* 右侧注册区域 */
.right-panel {
  width: 40%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #ffffff;
  padding: 0 80px;
}

.register-content {
  width: 100%;
  max-width: 420px;
}

.register-header {
  margin-bottom: 45px;
  text-align: center;
}

.register-title {
  font-size: 32px;
  font-weight: 600;
  color: #1a1a1a;
  margin: 0 0 8px 0;
}

.register-subtitle {
  font-size: 15px;
  color: #8c8c8c;
  margin: 0;
}

/* 表单样式 */
.register-form {
  width: 100%;
}

.register-form :deep(.el-form-item) {
  margin-bottom: 24px;
}

.input-item :deep(.el-input__wrapper) {
  border-radius: 6px;
  border: 1px solid #dcdee0;
  box-shadow: none;
  transition: all 0.3s ease;
  background: #fafbfc;
}

.input-item :deep(.el-input__wrapper:hover) {
  border-color: #409eff;
  background: white;
}

.input-item :deep(.el-input__wrapper.is-focus) {
  border-color: #409eff;
  background: white;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1);
}

.input-item :deep(.el-input__prefix) {
  padding-left: 14px;
}

.input-icon {
  color: #8c8c8c;
  font-size: 18px;
}

.captcha-row {
  display: flex;
  gap: 12px;
  align-items: flex-start;
  width: 100%;
}

.captcha-input {
  flex: 1;
  min-width: 0;
}

.captcha-input :deep(.el-input__wrapper) {
  border-radius: 6px;
  border: 1px solid #dcdee0;
  background: #fafbfc;
}

.captcha-input :deep(.el-input__wrapper:hover) {
  border-color: #409eff;
  background: white;
}

.captcha-input :deep(.el-input__wrapper.is-focus) {
  border-color: #409eff;
  background: white;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1);
}

.captcha-box {
  width: 100px;
  height: 40px;
  border: 1px solid #dcdee0;
  border-radius: 6px;
  cursor: pointer;
  overflow: hidden;
  transition: all 0.3s ease;
  background: #fafbfc;
  flex-shrink: 0;
}

.captcha-box:hover {
  border-color: #409eff;
  background: white;
}

.captcha-canvas {
  width: 100%;
  height: 100%;
  display: block;
}

/* 复选框样式 */
.checkbox-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.remember-checkbox,
.privacy-checkbox {
  margin: 0;
  font-size: 14px;
  color: #606266;
}

.privacy-link {
  color: #409eff;
  cursor: pointer;
  transition: color 0.3s ease;
}

.privacy-link:hover {
  color: #67c23a;
}

/* 注册按钮 */
.register-button {
  width: 100%;
  height: 50px;
  border-radius: 6px;
  font-size: 16px;
  font-weight: 500;
  background: #409eff;
  border: none;
  transition: all 0.3s ease;
  margin-bottom: 24px;
  margin-top: 8px;
}

.register-button:hover {
  background: #66b1ff;
}

.register-button:active {
  transform: translateY(1px);
}

/* 登录链接 */
.action-links {
  text-align: center;
  margin-top: 20px;
  font-size: 14px;
  color: #8c8c8c;
}

.login-link {
  color: #8c8c8c;
}

.login-link span {
  color: #409eff;
  font-weight: 500;
  cursor: pointer;
  transition: color 0.3s ease;
  margin-left: 4px;
}

.login-link span:hover {
  color: #67c23a;
}

/* 隐私协议内容 */
.privacy-content {
  max-height: 500px;
  overflow-y: auto;
  padding: 20px 10px;
  line-height: 1.8;
}

.privacy-content h3 {
  color: #303133;
  font-size: 16px;
  font-weight: 600;
  margin: 20px 0 12px 0;
}

.privacy-content p {
  color: #606266;
  font-size: 14px;
  margin: 12px 0;
}

.privacy-content ul {
  margin: 12px 0;
  padding-left: 24px;
}

.privacy-content li {
  color: #606266;
  font-size: 14px;
  margin: 8px 0;
}

/* 响应式设计 */
@media (max-width: 992px) {
  .register-container {
    flex-direction: column;
  }

  .left-panel {
    width: 100%;
    height: 400px;
  }

  .right-panel {
    width: 100%;
    padding: 60px 50px;
  }

  .brand-header {
    left: 30px;
    top: 30px;
  }

  .brand-title {
    font-size: 28px;
  }

  .brand-subtitle {
    font-size: 14px;
  }

  .logo-icon {
    width: 48px;
    height: 48px;
  }

  .company-info {
    left: 30px;
    bottom: 30px;
  }

  .company-name {
    font-size: 20px;
  }

  .company-slogan {
    font-size: 12px;
  }
}

@media (max-width: 576px) {
  .left-panel {
    height: 300px;
  }

  .brand-header {
    left: 20px;
    top: 20px;
    gap: 12px;
  }

  .brand-title {
    font-size: 24px;
  }

  .brand-subtitle {
    font-size: 13px;
  }

  .logo-icon {
    width: 44px;
    height: 44px;
  }

  .company-info {
    left: 20px;
    bottom: 20px;
  }

  .company-name {
    font-size: 18px;
  }

  .company-slogan {
    font-size: 11px;
  }

  .register-title {
    font-size: 26px;
  }

  .register-subtitle {
    font-size: 13px;
  }

  .right-panel {
    padding: 40px 30px;
  }

  .register-header {
    margin-bottom: 35px;
  }
}

/* 注册关闭提示样式 */
.registration-disabled {
  text-align: center;
  padding: 40px 20px;
}

.disabled-icon {
  margin-bottom: 30px;
  color: #909399;
}

.disabled-title {
  font-size: 28px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 20px 0;
}

.disabled-description {
  font-size: 16px;
  color: #606266;
  margin: 0 0 10px 0;
  line-height: 1.6;
}

.disabled-tip {
  font-size: 14px;
  color: #909399;
  margin: 0 0 40px 0;
}

.disabled-actions {
  display: flex;
  justify-content: center;
}
</style>
